import React, { useEffect, useState } from 'react'
import moment from 'moment';

export default function Clock() {
  //声明一个状态
  let [timeStr, setTimeStr] = useState(moment().format('YYYY-MM-DD HH:mm:ss'));

  //模拟 componentDidMount
  useEffect(() => {
    console.log('mount');
    //启动定时器
    let timer = setInterval(() => {
      console.log(moment().format('YYYY-MM-DD HH:mm:ss'));
      //更新状态
      setTimeStr(moment().format('YYYY-MM-DD HH:mm:ss'));
    }, 1000);
    //window 绑定事件  右键菜单事件
    window.oncontextmenu = function(e){
      e.preventDefault();
    }

    //返回一个函数 模拟 componentWillUnmount
    return () => {
      console.log('unmount')
      clearInterval(timer);
      //恢复右键的功能
      window.oncontextmenu = null;
    }
  }, []);

  return (
    <div style={{padding: 20, border: 'solid 1px #234'}}>
      {timeStr}
    </div>
  )
}
